package me.wangqu.weiyouqu.web.rest.business.dao.impl;

import me.wangqu.weiyouqu.web.rest.business.dao.SignDao;
import me.wangqu.weiyouqu.web.rest.util.constant.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by joln on 2016/6/24.
 */

@Repository

public class SignDaoImpl implements SignDao {
    private final Logger log = LoggerFactory.getLogger(SignDaoImpl.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public boolean isSignEnable(String login) {
        log.debug("判断今天是否可以签到");
        if (!ObjectUtils.isEmpty(login)) {
            StringBuffer sql = new StringBuffer(256);
            List<Object> params = new ArrayList<Object>();
            sql.append("SELECT count(r.id) FROM refererdata r WHERE r.uid = ( SELECT u.id FROM userdata u WHERE u.phone =? ) AND r.day = CURDATE()  AND r.aid = ? ");
            params.add(login);
            params.add(0);
            return jdbcTemplate.queryForObject(sql.toString(), params.toArray(), Integer.class) == 0;
        }
        return false;

    }

    @Override
    public boolean sign(String login, BigDecimal amount, String ip) {
        log.debug("签到");
        if (!ObjectUtils.isEmpty(login) && !ObjectUtils.isEmpty(amount)) {
            StringBuffer sql = new StringBuffer(256);
            List<Object> params = new ArrayList<Object>();
            sql.append("INSERT INTO `refererdata` (`uid`, `aid`, `title`, `long`, `money`");
            sql.append("	, `width`, `height`, `ip`, `day`, `time`)");
            sql.append("VALUES ((SELECT u.id from userdata u where u.phone = ?), ?, ?, '', ?");
            sql.append("	, '', '', ?, CURDATE(), CURRENT_TIMESTAMP())");
            params.add(login);
            params.add(Constant.REFERERDATA_AID_SIGN);
            params.add("签到");
            params.add(amount);
            params.add(ip);
            if (jdbcTemplate.update(sql.toString(), params.toArray()) > 0) {
                //签到增加余额
                sql = new StringBuffer();
                params = new ArrayList<Object>();
                sql.append("UPDATE userdata u ");
                sql.append(" SET ");
                sql.append("u.money=u.money+?,");
                sql.append("u.income=u.income+? ");
                sql.append(" WHERE ");
                sql.append("u.phone=?");
                params.add(amount);
                params.add(amount);
                params.add(login);
                return jdbcTemplate.update(sql.toString(), params.toArray()) > 0;

            }
        }
        return false;
    }
}

